package pers.whj.stack;

public class LinkStack<T> {
    private Node mHead;
    private Node mRear;

    class Node {
        T data;
        Node next;

        public Node(T data) {
            this.data = data;
            this.next = null;
        }
    }

    public LinkStack() {
        mHead = null;
        mRear = null;
    }

    public boolean isEmpty() {
        return mHead == null && mRear == null;
    }

    public void push(T data) {
        Node node = new Node(data);
        if (isEmpty()) {
            mHead = node;
        } else {
            mRear.next = node;
        }
        mRear = node;
    }

    public T pop() {
        if (isEmpty()) {
            return null;
        } else {
            Node temp = mHead;
            if (mHead == mRear) {
                mHead = null;
                mRear = null;
                return temp.data;
            } else {
                while (temp.next != null) {
                    if (temp.next.next == null) {
                        break;
                    }
                    temp = temp.next;
                }
                T data = mRear.data;
                mRear = temp;
                mRear.next = null;
                return data;
            }
        }
    }

    public T getTop() {
        if (isEmpty()) {
            return null;
        } else {
            return mRear.data;
        }
    }
}